import React, { useState } from 'react';
import { Form, Input, Button, Checkbox, message } from 'antd';
import { UserOutlined, LockOutlined, CodeOutlined } from '@ant-design/icons';
import { LoginLayout } from '../../g-index/LoginLayout';
import { LoginParams } from '../../g-types/user';
import { LoginApi } from './server';
import './index.less';

/**
 * 登录页面
 * @returns 登录页面组件
 */
export const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);

  // 处理登录
  const handleLogin = async (values: LoginParams) => {
    try {
      setLoading(true);
      
      // 校验用户名和密码
      if (values.username === 'admin' && values.password === '6666') {
        // 登录成功
        const result = await LoginApi.login(values);
        
        // 保存登录状态
        localStorage.setItem('token', result.token);
        localStorage.setItem('user', JSON.stringify(result.user));
        
        message.success('登录成功');
        
        // 跳转到首页
        window.location.href = '/dashboard';
      } else {
        message.error('用户名或密码错误');
      }
    } catch (error) {
      console.error('登录失败', error);
      message.error('登录失败，请稍后再试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <LoginLayout>
      <div className="login-title">
        <CodeOutlined className="login-icon" />
        <h1 className="login-name">模版开发者后台</h1>
      </div>
      <Form
        name="login"
        className="login-form"
        initialValues={{ remember: true }}
        onFinish={handleLogin}
      >
        <Form.Item
          name="username"
          rules={[{ required: true, message: '请输入用户名' }]}
        >
          <Input
            prefix={<UserOutlined />}
            placeholder="用户名"
            size="large"
            autoComplete="username"
          />
        </Form.Item>

        <Form.Item
          name="password"
          rules={[{ required: true, message: '请输入密码' }]}
        >
          <Input.Password
            prefix={<LockOutlined />}
            placeholder="密码"
            size="large"
            autoComplete="current-password"
          />
        </Form.Item>

        <Form.Item>
          <Form.Item name="remember" valuePropName="checked" noStyle>
            <Checkbox>记住我</Checkbox>
          </Form.Item>
          <a className="login-form-forgot" href="#">
            忘记密码
          </a>
        </Form.Item>

        <Form.Item>
          <Button
            type="primary"
            htmlType="submit"
            className="login-form-button"
            size="large"
            loading={loading}
          >
            登录
          </Button>
        </Form.Item>
      </Form>
    </LoginLayout>
  );
}; 